package com.nuoniu.sibanyun.service.production.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.erp.ErpWorkProcedure;
import com.nuoniu.sibanyun.entity.production.ErpStation;
import com.nuoniu.sibanyun.mapper.production.ErpStationMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpWorkProcedureService;
import com.nuoniu.sibanyun.service.production.IErpStationService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 工位 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-03-06
 */
@Service
public class ErpStationServiceImpl extends ServiceImpl<ErpStationMapper, ErpStation> implements IErpStationService {

    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private IErpWorkProcedureService workProcedureService;

    @Override
    public Page<ErpStation> pageList(Page page, ErpStation station) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account_id", accountService.getCurrentAccountId());
        wrapper.eq("company_id", userInfo.getCompanyId());
        return page(page, wrapper);
    }

    @Override
    public void saveStation(ErpStation station) {
        UserInfo userInfo = UserThreadLocal.get();
        ErpStation stationByCode = baseMapper.getByCode(userInfo.getCompanyId(), station.getCode());
        if(stationByCode != null && (station.getId() == null || !station.getId().equals(stationByCode.getId()))) {
            throw new NuoNiuException("编码不能重复");
        }

        ErpStation stationByName = baseMapper.getByName(userInfo.getCompanyId(), station.getName());
        if(stationByName != null && (station.getId() == null || !station.getId().equals(stationByName.getId()))) {
            throw new NuoNiuException("名称不能重复");
        }

        if(station.getId() == null) {
            station.setAccountId(accountService.getCurrentAccountId());
            station.setCompanyId(userInfo.getCompanyId());
        }
        saveOrUpdate(station);
    }

    @Override
    public void deleteById(Long id) {
        QueryWrapper<ErpWorkProcedure> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id", id);
        List<ErpWorkProcedure> workProcedures = workProcedureService.list(wrapper);
        if(workProcedures.size() > 0) {
            throw new NumberFormatException("已在工序中使用，不能删除");
        }
        this.removeById(id);
    }
}
